package cn.wangzg.httpurlconndemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.UrlQuerySanitizer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;

import cn.wangzg.httpurlconndemo.utils.HttpCallbackBytesListener;
import cn.wangzg.httpurlconndemo.utils.HttpCallbackStringListener;
import cn.wangzg.httpurlconndemo.utils.HttpUrlConnectionUtils;

public class MainActivity extends AppCompatActivity {
    private TextView textView;
    private String strUrl="https://www.runoob.com/w3cnote/android-tutorial-httpurlconnection.html";
    private String strUrlImage="https://www.runoob.com/wp-content/uploads/2015/09/49076488.jpg";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.textView);
    }
    //1.在主线程中直接调用，会报错
//    public void btnHtml(View v) {
//        String html = getHtml("https://www.runoob.com/w3cnote/android-tutorial-httpurlconnection.html");
//        textView.setText(html);
//    }
    //2.使用Thread+Handler进行异步调用
    //创建Handler对象，用来发送和处理消息
//    private Handler handler=new Handler(){
//        //处理消息
//        @Override
//        public void handleMessage(@NonNull Message msg) {
//            if(msg.what==1){
//                String html= (String) msg.obj;
//                textView.setText(html);
//            }
//        }
//    };

//    private static class MyHandler extends Handler {
//        private final WeakReference<MainActivity> mActivity;
//
//        public MyHandler(MainActivity activity) {
//            mActivity = new WeakReference<MainActivity>(activity);
//        }
//
//        @Override
//        public void handleMessage(Message msg) {
//            MainActivity activity = mActivity.get();
//            if (activity != null) {
//                if (msg.what == 1) {
//                    String html = (String) msg.obj;
//                    activity.textView.setText(html);
//                }
//            }
//        }
//    }
//    private final MyHandler handler = new MyHandler(this);
//    public void btnHtml(View v) {
//        //新建线程执行网络访问
//        new Thread() {
//            @Override
//            public void run() {
//                final String html = getHtml("https://www.runoob.com/w3cnote/android-tutorial-httpurlconnection.html");
//                //获得数据，发送消息，通知主线程更新数据
//                Message msg = new Message();
//                msg.what = 1;
//                msg.obj = html;
//                handler.sendMessage(msg);
//            }
//        }.start();
//    }

    //3.使用Thread+runOnUiThread
//    public void btnHtml(View v) {
//        new Thread(){
//            @Override
//            public void run() {
//                final String html = getHtml("https://www.runoob.com/w3cnote/android-tutorial-httpurlconnection.html");
//                //回到主线程执行更新操作
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        textView.setText(html);
//                    }
//                });
//            }
//        }.start();
//    }

    //4.使用AsyncTask
//    static class MyAsyncTask extends AsyncTask<String,Void,String>{
//        private WeakReference<MainActivity> activityReference;
//
//        // only retain a weak reference to the activity
//        MyAsyncTask(MainActivity context) {
//            activityReference = new WeakReference<>(context);
//        }
//        @Override
//        protected String doInBackground(String... strings) {
//            MainActivity activity = activityReference.get();
//            if(activity!=null) {
//                return activity.getHtml(strings[0]);
//            }else {
//                return null;
//            }
//        }
//
//        @Override
//        protected void onPostExecute(String s) {
//            MainActivity activity = activityReference.get();
//            if(activity!=null) {
//                activity.textView.setText(s);
//            }
//        }
//    }
//    public void btnHtml(View v) {
//        new MyAsyncTask(this).execute(strUrl);
//    }

    //5.使用自己封装的工具类
    public void btnHtml(View v) {
        HttpUrlConnectionUtils.doGet(this, strUrl,
                new HttpCallbackStringListener() {
                    @Override
                    public void onFinish(String response) {
                        textView.setText(response);
                    }

                    @Override
                    public void onError(Exception e) {
                        textView.setText("获取失败！");
                    }
                });
    }

    public void btnImage(View v) {
        new Thread() {
            @Override
            public void run() {
                final Drawable drawable = getDrawable(strUrlImage);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        textView.setCompoundDrawables(drawable, null, null, null);
                    }
                });
            }
        }.start();
    }
    //发送Get请求，获取流
    private InputStream httpGet(String strUrl) throws IOException {
        InputStream is = null;
        URL url = new URL(strUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");//默认值，可以省略
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        is = conn.getInputStream();
        return is;
    }
    //从网上获取网页源码
    private String getHtml(String strUrl) {
        InputStream is = null;
        try {
            is = httpGet(strUrl);
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            is.close();
            return new String(outStream.toByteArray(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    //从网上获取Bitmap
    private Bitmap getImage(String strUrl) {
        InputStream is = null;
        try {
            is = httpGet(strUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Bitmap bitmap = BitmapFactory.decodeStream(is);
        return bitmap;
    }
    //从网上获取Drawable
    private Drawable getDrawable(String strUrl) {
        InputStream is = null;
        try {
            is = httpGet(strUrl);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        Drawable drawable = Drawable.createFromStream(is, "image");
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth() * 2,
                drawable.getIntrinsicHeight() * 2);
        return drawable;
    }
    //Post请求，传递Json参数
    private InputStream httpPostJson(String strUrl,String strJson) throws Exception {
        InputStream is = null;
        URL url = new URL(strUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setUseCaches(false);

        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
        // 设置文件类型:
        conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
        conn.setRequestProperty("accept","application/json");
        // 往服务器里面发送数据
        if (strJson != null && !TextUtils.isEmpty(strJson)) {
            byte[] writebytes = strJson.getBytes();
            // 设置文件长度
            conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
            OutputStream outwritestream = conn.getOutputStream();
            outwritestream.write(strJson.getBytes());
            outwritestream.flush();
            outwritestream.close();
        }

        if(conn.getResponseCode()==200){
            is = conn.getInputStream();
        }
        return is;
    }
    //使用Post方式提交Json，用来新增一个用户
    public void btnPost(View view){
        final String strJson="{\"id\":7,\"name\":\"张三风\",\"age\":\"44\",\"email\":\"zhangsan@qq.com\"}";
        new Thread(){
            @Override
            public void run() {
                try {
                    InputStream is = httpPostJson("http://192.168.2.99:8080/users", strJson);
                    // 读取响应
                    BufferedReader reader = new BufferedReader(new
                            InputStreamReader(is));
                    String lines;
                    final StringBuffer sb = new StringBuffer("");
                    while ((lines = reader.readLine()) != null) {
                        lines = URLDecoder.decode(lines, "utf-8");
                        sb.append(lines);
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            textView.setText(sb.toString());
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
